package pl.edu.pw.MidEmu.Logic;

import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;

import pl.edu.pw.MidEmu.Common.Models.EthernetInterfaceModel;

/**
 * Service class responsible for configuring Ethernet interfaces
 * @author Mateusz Starodab
 *
 */
public class EthernetService
{
	/**
	 * Lists all available Ethernet interfaces
	 * @return List of Ethernet interfaces models
	 */
	public List<EthernetInterfaceModel> getAviableEthernetInterfaces()
	{
		ArrayList<EthernetInterfaceModel> list = new ArrayList<EthernetInterfaceModel>();

		try
		{
			Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
			while (interfaces.hasMoreElements())
			{
				NetworkInterface inter = interfaces.nextElement();
				Enumeration<InetAddress> addresses = inter.getInetAddresses();
				while (addresses.hasMoreElements())
				{
					InetAddress address = addresses.nextElement();
					if (address instanceof Inet4Address)
					{
						EthernetInterfaceModel model = new EthernetInterfaceModel(inter, (Inet4Address) address);
						list.add(model);
					}
				}
			}

		}
		catch (SocketException e)
		{
			e.printStackTrace();
		}

		return list;
	}

	/**
	 * Gets ethernet interface model by interface name
	 * @param name Name of the interface
	 * @return Ethernet interface model or null if non is found
	 */
	public EthernetInterfaceModel getIfaceByName(String name)
	{
		List<EthernetInterfaceModel> list = getAviableEthernetInterfaces();

		for (EthernetInterfaceModel model : list)
		{
			if (model.getName().equals(name))
				return model;
		}
		return null;
	}

	/**
	 * Counts available tap interfaces
	 * @return Number of TAP interfaces
	 */
	public String getTapAddressesCount()
	{
		int interfaceCount = 0;
		try
		{
			Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
			while (interfaces.hasMoreElements())
			{
				NetworkInterface inter = interfaces.nextElement();
				if (inter.getName().contains("tap"))
				{
					interfaceCount++;
				}
			}
		}
		catch (SocketException e)
		{
			e.printStackTrace();
		}
		return new Integer(interfaceCount).toString();
		
//		int interfaceCount = 0;
//		try
//		{
//			NetworkInterface inter = NetworkInterface.getByName("lo");
//			Enumeration<InetAddress> addresses = inter.getInetAddresses();
//			while (addresses.hasMoreElements())
//			{
//				InetAddress address = addresses.nextElement();
//				if(address instanceof Inet4Address)
//				{
//					interfaceCount++;
//				}
//			}
//		}
//		catch (SocketException e)
//		{
//			e.printStackTrace();
//		}
//		return new Integer(interfaceCount).toString();
	}
}
